<template>
  <div id="amapMap">
    <el-amap-search-box
      :search-option="searchOption"
      :on-search-result="onSearchResult"
      :citylimit="false"
      class="search-box">
    </el-amap-search-box>
    <el-amap
      :loading="loading"
      ref="map"
      :mapStyle="theme"
      cursor="pointer"
      vid="vueAmap"
      :center="mapCenter"
      :zoom="zoom"
      :plugin="plugin"
      :events="events">
      <el-amap-marker
        :position="mapCenter"
        :events="currentMarker.events"
        vid="marker">
      </el-amap-marker>
      <el-amap-info-window
        v-if="visible"
        :position="mapCenter"
        :visible="visible">
        <div v-html="content"></div>
      </el-amap-info-window>
      <el-amap-circle
        vid="circle"
        :center="mapCenter"
        :radius="80"
        fill-opacity="0.2"
        strokeColor="#38f"
        strokeOpacity="0.8"
        strokeWeight="1"
        fillColor="#38f"
      >
      </el-amap-circle>
    </el-amap>
  </div>
</template>
<script>
  //地图取点组件
  const Address = require('../utils/url');
  export default {
    name: "SelectMap",
    props: {
      center: {//初始位置
        type: Array,
        default: () => [116.397128, 39.916527]
      }
    },
    data() {
      return {
        zoom: 16,
        searchOption: "",
        visible: true,
        loading: true,
        content: "",
        mapCenter: [],
        theme: 'normal',//地图样式 normal（默认样式）、dark（深色样式）、light（浅色样式）、fresh(osm清新风格样式)、blue_night
        events: {
          init: (o) => {
            o.getCity(result => {
              this.transform(this.mapCenter.join(","));
            })
          },
          click: (e) => {
            this.mapCenter = [e.lnglat.lng, e.lnglat.lat];
            this.transform(this.mapCenter.join(","));
          }
        },
        currentMarker: {
          events: {
            click: (e) => {
              this.visible = !this.visible;
            }
          },
        },
        plugin: [
          {
            pName: 'ToolBar',//工具条插件
            position: 'LB',
          },
        ],
        msg: {},
      };
    },
    created() {
      this.mapCenter = this.center;
    },
    methods: {
      onSearchResult(pois) {
        if (pois.length > 0) {
          const center = {
            lng: pois[0].lng,
            lat: pois[0].lat
          };
          this.mapCenter = [center.lng, center.lat];
          this.transform(this.mapCenter.join(","));
        }
      },
      //根据经纬度获取周边
      transform(locations) {
        // 详情见高德地图开发文档 https://lbs.amap.com/api/webservice/guide/api/search#around
        const url = `${Address.SearchMap}?key=${Address.keyMap}&location=${locations}&offset=25&page=1`;
        this.loading = true;
        fetch(url)
          .then((res) => res.json())
          .then((response) => {
            this.loading = false;
            if (response.status === '1') {
              this.visible = response.pois.length !== 0;
              this.msg = response.pois.length === 0 ? {} : response.pois[0];
              // console.log(this.msg);
            }
            else {
              // Error(`错误代码:${response.infocode}`);
            }
          })
          .catch((error) => {
            this.loading = false;
            // Error(`错误代码:${error.infocode}`);
          });
      },
    },
    watch: {
      msg(val) {
        const pname = val.pname && val.pname !== null ? val.pname : "";//省
        const cityname = val.cityname && val.cityname !== null ? val.cityname : "";//市
        const adname = val.adname && val.adname !== null ? val.adname : "";//区
        const address = val.address && val.address !== null ? val.address : "";//详细地址
        const name = val.name && val.name !== null ? val.name : "";//地点名称
        this.content = `<b>${name}</b><br/><p>${pname}${cityname}${adname}${address}</p>`;
        this.$emit("getMapInfo", val);
      }
    }
  };
</script>
<style scoped>
  #amapMap {
    position: relative;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    width: 100%;
    height: 400px;
    overflow: hidden;
  }

  .search-box {
    width: 300px;
    height: 35px;
    position: absolute;
    top: 15px;
    left: 15px;
  }
</style>
